package com.xqc.provider.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class XqcDataSourceConfig {

    @Value("${mybatis-plus.mapper-locations:}")
    private String mybatisMapperLocations;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * Seata 是通过代理数据源实现事务分支，所以需要先配置一个数据源的代理，否则事务不会回滚
     * @param druidDataSource
     * @return
     */
    @Bean
    public DataSourceProxy dataSourceProxy(DruidDataSource druidDataSource){
        return new DataSourceProxy(druidDataSource);
    }

    /**
     * 解决seata代理数据源后mybatisplus的增强组件全部失效的bug
     * @param dataSourceProxy
     * @return
     * @throws Exception
     */
   /* @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSourceProxy);
        factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(this.mybatisMapperLocations));
        return factory.getObject();
    }*/

    /**
     * 配置全局事务扫描器。有两个参数，一个是应用名称，一个是事务分组。
     * @return
     */
//    @Bean
//    public GlobalTransactionScanner globalTransactionScanner(){
//       return new  GlobalTransactionScanner("activiti-service","my_test_tx_group");
//    }

    /**
     *redis序列化设置，spring-data-redis的RedisTemplate默认是JdkSerializationRedisSerializer来进行序列化，值是十六进制，例如本身要存的key:tb，但实际上存的是\xac\xed\x00\x05t\x00\tb
     */
    @Bean
    public RedisTemplate<String, Object> setRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setConnectionFactory(factory);
        // 自定义Jackson2JsonRedisSerializer
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}
